from flask import Flask, request, jsonify, send_file, render_template
from smart_scraper import SmartResumeScraper
import os
import threading
import uuid

app = Flask(__name__)
app.config['EXPORT_FOLDER'] = 'downloads'
os.makedirs(app.config['EXPORT_FOLDER'], exist_ok=True)

# 全局任务存储
active_tasks = {}

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/start', methods=['POST'])
def start_crawl():
    data = request.json
    urls = [u.strip() for u in data.get('urls', []) if u.strip()]
    max_workers = min(int(data.get('workers', 3)), 10)
    
    if not urls:
        return jsonify({"error": "至少需要输入一个URL"}), 400

    # 生成任务ID
    task_id = str(uuid.uuid4())
    
    # 创建爬虫实例
    scraper = SmartResumeScraper()
    
    # 在后台线程运行爬取任务
    def run_task():
        try:
            output_file = os.path.join(app.config['EXPORT_FOLDER'], f'result_{task_id}.xlsx')
            scraper.scrape_multiple(
                urls=urls,
                output_file=output_file,
                max_workers=max_workers
            )
            active_tasks[task_id] = {
                'status': 'completed',
                'file': output_file,
                'stats': {
                    'total': len(scraper.data),
                    'success': sum(1 for item in scraper.data if '错误信息' not in item)
                }
            }
        except Exception as e:
            active_tasks[task_id] = {'status': 'error', 'message': str(e)}

    thread = threading.Thread(target=run_task)
    thread.start()
    
    active_tasks[task_id] = {'status': 'running'}
    return jsonify({"task_id": task_id})

@app.route('/api/status/<task_id>')
def check_status(task_id):
    task = active_tasks.get(task_id, {})
    return jsonify(task)

@app.route('/api/download/<task_id>')
def download_result(task_id):
    task = active_tasks.get(task_id, {})
    if task.get('status') != 'completed':
        return jsonify({"error": "任务未完成"}), 404
    
    return send_file(
        task['file'],
        as_attachment=True,
        download_name='resume_data.xlsx',
        mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)